<template>
  <div>
    <div v-for="(item) in orderGoodriesList" :key="item.id" style="position:relative;overflow:hidden;width: 360px;" class="print-card">
      <template v-if="needIngredient">
        <div v-for="(page) in item.pages" :key="item.id" class="page">
          <div style="height: 445px;overflow: hidden;">
            <!-- 配料表 -->
            <ingredient v-if="page.ingredient" :style="getIngredientStyle(page)" style="margin-bottom:10px;overflow: hidden;"
              v-bind:CookieTemplateList="page.ingredient" :orderDetail="item"></ingredient>
            <!-- 订单信息 -->
            <baseinfo v-if="page.baseinfo" :item="item" :key="item.id" :needIngredient="needIngredient"></baseinfo>
          </div>
          <blessings v-if="needBlessings && page.blessings" :item="item" style="margin-top:20px;"></blessings>
        </div>
      </template>
      <template v-if="!needIngredient">
        <div v-for="(page) in item.pages" :key="item.id" class="page">
          <!-- 订单信息 -->
          <baseinfo v-if="page.baseinfo" :item="item" :key="item.id" :needIngredient="needIngredient"></baseinfo>
          <blessings v-if="needBlessings && page.blessings" :item="item" style="margin-top:20px;"></blessings>
        </div>
      </template>
    </div>
    <button ref="empty">用于去除打印按钮foucs</button>
  </div>
</template>

<script>
import baseinfo from './components/baseinfo';
import blessings from './components/blessings';
import ingredient from "./components/ingredient";
import {
  orderPrinting, // 批量打印
  orderPrintingFrequency,  // 批量打印信息
} from '@/api/shop';
import { query } from "@/api/user"; // 查询生产打印机设备
import { printingDisabledCtrl } from '@/util/print'
import { lodoper } from '@/util/print'
export default {
  components: { baseinfo, blessings, ingredient },
  props: {
    needBlessings: {
      type: Boolean,
    },
    needIngredient: {
      type: Boolean,
    },
    isOpenPrintPreview: {
      type: Boolean,
    }
  },
  data() {
    return {
      orderGoodriesList: [],
    }
  },
  mounted() {
  },
  created() {
  },
  watch: {},
  methods: {
    // 查询打印机
    queryPrinter() {
      let formInline = {
        type: 1,
        key: '[1,2]',
        userId: JSON.parse(window.localStorage.getItem("saber-userInfo")).content.account
      }
      return query(formInline).then(res => {
        if (res.data.msg == '执行成功' && res.data.data && res.data.data.length != 0) {
          const printerValue = res.data.data[0].value
          const printerList = printerValue ? JSON.parse(printerValue) : []
          return printerList
        } else {
          throw new Error('请到系统模块中的打印机设置中添加打印机')
        }
      })
    },
    // 获取需要打印的订单
    async getPrintOrderList(orderDetailIdList, orderDetailList) {
      const printOrderRes = await orderPrinting(orderDetailIdList)
      if (printOrderRes.data.code == 200) {
        const orderGoodriesList = printOrderRes.data.data
        this.parseGoodsData(orderGoodriesList, orderDetailList)
        this.parsePagesByOrder(orderGoodriesList)
        return orderGoodriesList
      } else {
        throw new Error('打印订单查询失败，请重试！')
      }
    },
    // 判断没有配料表的订单
    judgeNoProdOrders(orderList) {
      if (orderList && orderList.length) {
        const noProductions = orderList.filter(item => item.nutrients != 1)
        if (noProductions && noProductions.length) {
          throw new Error(`打印失败，${noProductions.map(item => `【${item.goodsName}】`).join(',')}无配料表`)
        }
      }
    },
    // 配料表情况确认
    confirmIngredientTip(orderList) {
      let tip = '';
      orderList.forEach(item => {
        if (item.pages && item.pages.length > 1) {
          const count = item.pages.length;
          const isOverNumber = item.pages.filter(item => item.ingredient && item.ingredient.length >= 400);
          const isMulipleIngredient = item.goodsSkuProductions && item.goodsSkuProductions.length > 1;
          const detail = `${isOverNumber ? '配料表字数超过400，' : ''}${isMulipleIngredient ? `含${item.goodsSkuProductions.length}个配料表，` : ''}`
          tip = tip + `<div>[${item.xmbzNo}] [${item.goodsName}]，${detail ? detail : ''}将打印${count}张标签。</div>`
        }
      })
      if (tip) {
        return this.$confirm(tip, "请确认是否打印？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          dangerouslyUseHTMLString:true, // 注意此属性
        }).catch((error) => {
          throw new Error('已取消打印')
        })
      }
    },
    // 解析打印数据
    parseGoodsData(printGoodsList, orderDetailList) {
      printGoodsList.forEach(item => {
        const sameItem = orderDetailList.find($0 => $0.id === item.id)
        if (sameItem) {
          item.isDance = sameItem.isDance
        }
      })
    },
    // 打印插件打印
    lodopPrint(printerList, time) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          var printDom = this.$el
          lodoper.init({// 初始化
            pageWidth: '101.6mm',
            pageHeight: `${this.needIngredient ? '152' : '90'}mm`,
            strPageName: 'USER',
            printer: printerList[0], // 指定打印机
            fileName: '生产订单',// 打印任务名
          });
          const printCards = printDom.querySelectorAll('.print-card .page')
          if (printCards && printCards.length) {
            printCards.forEach(card => {
              lodoper.buildPage(card, {
                top: '1%', left: '1%', width: '98%', height: '98%'
              })
            })
          }
          lodoper.print(this.isOpenPrintPreview ? 'PREVIEW' : 'PRINT').then((value) => {
            resolve(value)
          })
        }, time || 1000)
      })
    },
    // 唤起打印
    async callPrint(orderDetailList, waitTime) {
      const orderDetailIdList = orderDetailList.map(item => item.id)
      this.$refs.empty.focus()
      try {
        if (orderDetailIdList.some(item => !item)) {
          throw new Error('未获取到打印数据，请重新选择')
        }
        this.needIngredient && this.judgeNoProdOrders(orderDetailList) // 无配料表throw

        printingDisabledCtrl(true)
        this.$notify({
          title: "提示",
          message: "请求打印中，请稍等...",
          type: "success",
          duration: 2000
        });
        setTimeout(() => {
          printingDisabledCtrl(false)
        }, 2000)
        const printerList = await this.queryPrinter() // 查询打印机
        this.orderGoodriesList = await this.getPrintOrderList(orderDetailIdList, orderDetailList) // 查询打印的订单数据
        if (this.needIngredient) {
          await this.confirmIngredientTip(this.orderGoodriesList) // 确认多张配料表
        }
        const printRes = await this.lodopPrint(printerList, waitTime)
        if (printRes !== '0' && printRes) {
          const recordPrintRes = await orderPrintingFrequency(orderDetailIdList)
          this.$notify({
            title: '打印成功',
            message: '请您耐心等待',
            type: 'success'
          })
          this.$emit('printSuccess')
          return true
        } else {
          throw new Error('打印失败，请重试！')
        }
      } catch (error) {
        console.error(error)
        this.$message.warning(error.message || '打印失败，请检查是否安装好驱动和已经连接打印机，或重新打印！');
        return false
      } finally {
        printingDisabledCtrl(false)
      }
    },
    // 解析订单的打印标签页数
    parsePagesByOrder(orderList) {
      orderList.forEach(order => {
        if (order.goodsSkuProductions && order.goodsSkuProductions.length > 0 && this.needIngredient) {
          let pages = []
          // 配料表字数 < 400，同一张纸可以打印下基础信息
          const baseInfoIndex = order.goodsSkuProductions.findIndex(item => item.ingredient.length < 400)
          if (baseInfoIndex < 0) {
            pages.push({
              baseinfo: true,
              blessings: this.needBlessings,
            })
          }
          pages = pages.concat(order.goodsSkuProductions.map((item, index) => {
            return {
              baseinfo: index === baseInfoIndex,
              blessings: index === baseInfoIndex,
              ingredient: item,
            }
          }))
          order.pages = pages
        } else {
          order.pages = [{
            baseinfo: true,
            blessings: this.needBlessings,
          }]
        }
      })
    },
    loading(isLoading) {
      if (isLoading) {
        this.loadingInstance = this.$loading({
          lock: true,
          text: '请求打印中，请稍等...',
        });
      } else {
        this.loadingInstance && this.loadingInstance.close()
      }
    },
    getIngredientStyle(page) {
      return page.baseinfo ? 'max-height: 240px;' : 'max-height: 445px;'
    }
  },
}
</script>

<style lang='scss'></style>
